#
# peerscape.profile.picture
#
# Copyright 2008 Helsinki Institute for Information Technology
# and the authors.
#
# Authors: Ken Rimey <rimey@hiit.fi>
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

"""
Get or set picture for personal or group profile.

The profile picture is typically jpeg.  It is optional and always public.

>>> from peerscape import DB
>>> db = DB()
>>> p = db.init_persona('Test User')
>>> db.get_profile_picture(p) is None
True

>>> db.set_profile_picture(p, ':-)')
u'/info/pic.dat'
>>> db.get_profile_picture(p)
u'/info/pic.dat'
>>> db.get(p, u'/info/pic.dat')
':-)'

>>> from binascii import unhexlify
>>> gif_data = unhexlify('474946383961010001000000003b')
>>> db.set_profile_picture(p, gif_data)
u'/info/pic.gif'
>>> db.get_profile_picture(p)
u'/info/pic.gif'
>>> db.get(p, u'/info/pic.gif') == gif_data
True

>>> db.get_last_event(p)['comment']
u'Updated profile picture.'
>>> db.post_event(p, 'Testing...')
>>> db.set_profile_picture(p, gif_data)
u'/info/pic.gif'
>>> db.get_last_event(p)['comment']
u'Testing...'

>>> db.clear_profile_picture(p)
>>> db.get_profile_picture(p) is None
True

>>> db.get_last_event(p)['comment']
u'Removed profile picture.'
>>> db.post_event(p, 'Testing...')
>>> db.clear_profile_picture(p)
>>> db.get_last_event(p)['comment']
u'Testing...'

>>> db.close()
"""

from __future__ import with_statement

import imghdr

FOLDER = u'/info/'
BASE = u'pic.'

class ProfilePictureDBMixin(object):
    def get_profile_picture(self, iid):
        """Return the path of the profile picture (or None)."""
        for path in self._list_pictures(iid):
            return path         # Return first one found.
        else:
            return None

    def set_profile_picture(self, iid, data):
        """Set the profile picture from the provided image data."""
        with self.write_transaction():
            before = self.get_current_mark()

            if not data:
                path = None
            else:
                path = FOLDER + BASE + get_image_extension(data)
                self.put(iid, path, data)

            for other in self._list_pictures(iid):
                if other != path:
                    self.delete(iid, other)

            after = self.get_current_mark()
            if before != after:
                if data:
                    self.post_event(iid, 'Updated profile picture.')
                else:
                    self.post_event(iid, 'Removed profile picture.')

            return path

    def clear_profile_picture(self, iid):
        """Remove any profile picture."""
        self.set_profile_picture(iid, None)

    def _list_pictures(self, iid):
        return [FOLDER + name for name in self.list(iid, FOLDER)
                if name.startswith(BASE)]

def get_image_extension(data):
    type = imghdr.what(None, data)
    if not type:
        return 'dat'
    elif type == 'jpeg':
        return 'jpg'
    else:
        return type

if __name__ == '__main__':
    import doctest
    doctest.testmod()
